const  express  =  require("express")
const  router  =  express.Router()
const conn = require("../mysql")

// 注册
router.get('/reg', (req, res) => {

    let { tel, pw, name } = req.query
    let sql = `select * from reg_login_goods where tel='${tel}'`
    conn.query(sql, (err, data) => {
        console.log(data);
        if (err) {
            console.log(err);
        } else {
            if (data.length) {
                //找到相应的用户
                res.send({
                    code: 0,
                    msg: '已注册'
                })
            } else {
                //没有找到，添加新用户
                console.log(1);
                let sql1 = `insert into reg_login_goods (name,tel,pw) values ('${name}',${tel},'${pw}')`
                console.log(sql);
                conn.query(sql1, (err, data) => {
                    if (err) {
                        console.log(err, '添加错误')
                    } else {
                        if (data.affectedRows == 1) {
                            res.send({
                                code: 1,
                                msg: '注册成功'
                            })
                        }
                    }
                })

            }
        }
    })
})

// 登录
router.get('/login', (req, res) => {
    let result = {}
    let { tel, pw } = req.query
    let sql = `select * from reg_login_goods where tel='${tel}'`
    conn.query(sql, (err, data) => {
        console.log(data);
        if (err) {
            console.log(err);
        } else {
            if (data.length) {
                //如果找到该用户
                if (pw == data[0].pw) {
                    //身份验证通过
                    result = {
                        code: 1,
                        msg: '登录成功'
                    }
                } else {
                    //密码错误
                    result = {
                        code: 2,
                        msg: '密码错误'
                    }
                }
            } else {
                //没有注册
                result = {
                    code: 3,
                    msg: '用户未注册'
                }
            }
        }
        res.send(result)
    })
})


module.exports  =  router;